<?php

namespace App\Http\Controllers\Freelancer;

use App\Http\Controllers\Controller;
use App\Jobs\VerifyFreelancerFourElementsJob;
use App\Models\Freelancer;
use App\Models\Task;
use App\Models\TaskApplication;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;

class TaskController extends Controller
{
    /**
     * 获取任务详情
     */
    public function show($id)
    {
        try {
            $task = Task::with('tenant')
                ->where('id', $id)
                ->where('status', 'active')
                ->first();

            if (!$task) {
                return response()->json([
                    'code' => 1,
                    'message' => '任务不存在或已结束',
                    'data' => null
                ]);
            }

            return response()->json([
                'code' => 0,
                'message' => '获取成功',
                'data' => [
                    'id' => $task->id,
                    'name' => $task->name,
                    'service_type' => $task->service_type,
                    'status' => $task->status,
                    'start_time' => $task->start_time,
                    'end_time' => $task->end_time,
                    'min_fee' => $task->min_fee,
                    'max_fee' => $task->max_fee,
                    'work_location' => $task->work_location,
                    'age_requirement' => ($task->min_age && $task->max_age) ? "{$task->min_age}岁-{$task->max_age}岁" : '不限',
                    'gender_requirement' => $this->formatGender($task->gender_requirement),
                    'education_requirement' => $this->formatEducation($task->education_requirement),
                    'description' => $task->work_content ?: $task->description ?? '',
                    'tenant_name' => $task->tenant->name,
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 1,
                'message' => '获取任务详情失败',
                'data' => null
            ]);
        }
    }

    /**
     * 申请任务
     */
    public function applyTask(Request $request)
    {
        /** @var Freelancer $user */
        $user = $request->user();
        $isVerified = $user->verification_status === Freelancer::VERIFICATION_APPROVED;

        $rules = [
            'taskId' => 'required|string',
            'experience' => 'nullable|string|max:500',
        ];

        if (! $isVerified) {
            $rules = array_merge($rules, [
                'name' => 'required|string|max:50',
                'idCard' => 'required|string|size:18',
                'bankCard' => 'required|string|max:30',
                'address' => 'required|string|max:200',
            ]);
        }

        $validator = Validator::make($request->all(), $rules);

        if ($validator->fails()) {
            return response()->json([
                'code' => 1,
                'message' => '参数验证失败',
                'data' => $validator->errors()
            ]);
        }

        try {
            $taskId = $request->taskId;

            // 检查是否已经申请过该任务
            $existingApplication = TaskApplication::where('freelancer_id', $user->id)
                ->where('task_id', $taskId)
                ->first();

            if ($existingApplication) {
                return response()->json([
                    'code' => 1,
                    'message' => '您已经申请过该任务',
                    'data' => null
                ]);
            }

            // 检查任务是否存在且有效
            $task = Task::find($taskId);
            if (!$task || $task->status !== 'active') {
                return response()->json([
                    'code' => 1,
                    'message' => '任务不存在或已结束',
                    'data' => null
                ]);
            }

            $name = $isVerified
                ? ($user->name ?? '')
                : trim((string) $request->input('name'));

            $idCard = $isVerified
                ? (string) $user->id_card
                : trim((string) $request->input('idCard'));

            $address = $isVerified
                ? (string) ($user->address ?? '')
                : trim((string) $request->input('address'));

            $bankCard = $isVerified
                ? (string) ($user->bank_account ?? '')
                : trim((string) $request->input('bankCard'));

            if ($isVerified && (! $name || ! $idCard || ! $address || ! $bankCard)) {
                return response()->json([
                    'code' => 1,
                    'message' => '实名认证信息不完整，请联系管理员处理',
                    'data' => null,
                ]);
            }

            if (! $isVerified) {
                $user->fill([
                    'name' => $name,
                    'id_card' => $idCard,
                    'address' => $address,
                    'bank_account' => $bankCard,
                ]);

                if ($user->isDirty(['name', 'id_card', 'address', 'bank_account'])) {
                    $user->verification_status = Freelancer::VERIFICATION_PENDING;
                    $user->save();
                } elseif ($user->verification_status !== Freelancer::VERIFICATION_APPROVED) {
                    $user->verification_status = Freelancer::VERIFICATION_PENDING;
                    $user->save();
                }

                VerifyFreelancerFourElementsJob::dispatch($user->id);
            }

            $tenantId = $task->tenant_id;
            $email = $user->email ?? '';
            $gender = $user->gender ?: null;
            $birthDate = $user->getAttribute('birth_date') ?: null;

            // 创建任务申请记录
            $application = TaskApplication::create([
                'freelancer_id' => $user->id,
                'task_id' => $taskId,
                'tenant_id' => $tenantId,
                'name' => $name,
                'email' => $email,
                'phone' => $user->phone,
                'id_card' => $idCard,
                'gender' => $gender,
                'birth_date' => $birthDate,
                'experience' => $request->experience,
                'status' => 'pending',
                'applied_at' => now(),
            ]);

            return response()->json([
                'code' => 0,
                'message' => '申请提交成功，请等待审核',
                'data' => [
                    'application_id' => $application->id,
                    'status' => $application->status,
                ]
            ]);
        } catch (\Exception $e) {
            Log::info('applyTask failed', [$e->getFile(),$e->getLine(),$e->getMessage()]);
            return response()->json([
                'code' => 1,
                'message' => '申请提交失败，请稍后重试',
                'data' => null
            ]);
        }
    }

    public function latestApplication(Request $request, $taskId)
    {
        $user = $request->user();

        if (! $user) {
            return response()->json([
                'code' => 1,
                'message' => '未登录或身份已失效',
                'data' => null,
            ]);
        }

        $userId = (string)($user->id);
        $taskApp = TaskApplication::where('task_id', $taskId)
            ->where('freelancer_id', (string)($userId))
            ->orderBy('id', 'desc')
            ->first();

        if (! $taskApp) {
            Log::info('[TaskController] latestApplication not found', [
                'task_id' => $taskId,
                'freelancer_id' => $user->id,
                'application' => $taskApp,
            ]);
            return response()->json([
                'code' => 0,
                'message' => '暂无报名记录',
                'data' => null,
            ]);
        }

        return response()->json([
            'code' => 0,
            'message' => '获取成功',
            'data' => [
                'id' => $taskApp->id,
                'status' => $taskApp->status,
                'application_number' => $taskApp->application_number,
                'applied_at' => optional($taskApp->applied_at)->format('Y-m-d H:i:s'),
                'processed_at' => optional($taskApp->processed_at)->format('Y-m-d H:i:s'),
                'reviewed_at' => optional($taskApp->reviewed_at)->format('Y-m-d H:i:s'),
            ],
        ]);
    }

    private function formatEducation(?string $education): string
    {
        $map = [
            'unlimited' => '不限',
            'junior_high' => '初中',
            'high_school' => '高中',
            'college' => '大专',
            'bachelor' => '本科',
            'master' => '硕士',
            'doctor' => '博士',
        ];

        if ($education === null || $education === '') {
            return '不限';
        }

        return $map[$education] ?? $education;
    }

    private function formatGender(?string $gender): string
    {
        $map = [
            'male' => '男',
            'female' => '女',
            'unlimited' => '不限',
        ];

        if ($gender === null || $gender === '') {
            return '不限';
        }

        return $map[$gender] ?? $gender;
    }
}
